import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// http://localhost:8080/JavaWeb1907/user
@WebServlet("/user")
public class UserServlet extends HttpServlet {

	// 当访问UserServlet时候默认访问的就是service
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("UserServlet.service()");
		// 解决post乱码问题
		req.setCharacterEncoding("UTF-8");
		// /JavaWeb1907/user?method=deleteById&id=1
		// /JavaWeb1907/user?method=findAll
		String method = req.getParameter("method");
		if (method == null || "".equals(method)) {
			method = "findAll";
		}
		switch (method) {
		case "findAll":
			findAll(req, resp);
			break;
		case "deleteById":
			deleteById(req, resp);
			break;
		case "add":
			add(req, resp);
			break;
		case "search":
			search(req, resp);
			break;
		case "getUserAddPage":
			getUserAddPage(req, resp);
			break;
		case "toUpdate":
			toUpdate(req, resp);
			break;
		case "update":
			update(req, resp);
			break;
		default:
			break;
		}
		
	}

	private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		
		Connection connection = null;
		PreparedStatement statement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "UPDATE user set name=?,age=?,gender=? WHERE id=?";
			statement = connection.prepareStatement(sql);
			statement.setString(1, name);
			statement.setInt(2, Integer.parseInt(age));
			statement.setString(3, gender);
			statement.setInt(4, Integer.parseInt(id));;
			// 打印执行的sql语句
			System.out.println(statement);
			int count = statement.executeUpdate();
			if (count == 1) {
				System.out.println("修改成功");
			} else {
				System.out.println("修改失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, null);
		}
		
		resp.sendRedirect("/JavaWeb1907/user?method=findAll");
	}

	private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userId = req.getParameter("id");
		
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		User user = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "SELECT id,name,age,gender FROM user where id=?";
			statement = connection.prepareStatement(sql);
			statement.setInt(1, Integer.parseInt(userId));
			System.out.println(statement);
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				String gender = resultSet.getString("gender");
				user = new User(id, name, age, gender);
			}
		}  catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, resultSet);
		}
		
		req.setAttribute("user", user);
		req.getRequestDispatcher("/user_update.jsp").forward(req, resp);
	}

	private void getUserAddPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ArrayList<Dept> list = new ArrayList<Dept>();
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection conection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=UTF-8", "root", "1234");
			String sql = "SELECT id,name FROM dept";
			PreparedStatement statement = conection.prepareStatement(sql);
			ResultSet resultSet = statement.executeQuery();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				Dept dept = new Dept(id, name);
				list.add(dept);
			}

			for (Dept dept : list) {
				System.out.println(dept);
			}
			// 6、关闭连接
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		// 把list集合放到request（一块内存）里面
		req.setAttribute("list", list);
		req.getRequestDispatcher("/user_add.jsp").forward(req, resp);
	}

	private void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String searchName = req.getParameter("searchName");
		
		ArrayList<User> list = new ArrayList<User>();
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "SELECT id,name,age,gender FROM user where name like ?";
			statement = connection.prepareStatement(sql);
			statement.setString(1, "%" + searchName + "%");
			System.out.println(statement);
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				String gender = resultSet.getString("gender");
				User user = new User(id, name, age, gender);
				list.add(user);
			}

			for (User user : list) {
				System.out.println(user);
			}
			// 6、关闭连接
		}  catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, resultSet);
		}
		
		// 把list集合放到request（一块内存）里面
		req.setAttribute("list", list);
		// 转发到user_list.jsp页面进行展示
		req.getRequestDispatcher("/user_list.jsp").forward(req, resp);
	}

	private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("UserServlet.add()");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		String deptId = req.getParameter("deptId");
		
		Connection connection = null;
		PreparedStatement statement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "INSERT user(name,age,gender,dept_id) VALUES(?,?,?,?)";
			statement = connection.prepareStatement(sql);
			statement.setString(1, name);
			statement.setInt(2, Integer.parseInt(age));
			statement.setString(3, gender);
			statement.setInt(4, Integer.parseInt(deptId));;
			// 打印执行的sql语句
			System.out.println(statement);
			int count = statement.executeUpdate();
			if (count == 1) {
				System.out.println("添加成功");
			} else {
				System.out.println("添加失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, null);
		}
		
		resp.sendRedirect("/JavaWeb1907/user?method=findAll");
	}

	private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		String id = req.getParameter("id");
		
		Connection connection = null;
		PreparedStatement statement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "DELETE FROM user WHERE id=?";
			statement = connection.prepareStatement(sql);
			statement.setInt(1, Integer.parseInt(id));
			int count = statement.executeUpdate();
			// 打印执行的sql语句
			System.out.println(statement);
			if (count == 1) {
				System.out.println("删除成功");
			} else {
				System.out.println("删除失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, null);
		}
		
		// 重定向就是告诉浏览器再发一个请求（查找所有）
		// 路径问题：
		// 如果这个请求是浏览器发送的这个项目名一定要写。
		// 如果请求是在服务器内部发送（转发）不需要写这个项目名
		// 理解：浏览器只能定位到tomcat服务器，不能定位到哪个项目
		// 代码是在服务器内部本身就运行在这个项目下边，不需要项目名
		resp.sendRedirect("/JavaWeb1907/user?method=findAll");
		
		//req.getRequestDispatcher("/user?method=findAll").forward(req, resp);;
	}

	private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ArrayList<User> list = new ArrayList<User>();
		try {
			// 1、加载驱动Class.forName("");
			Class.forName("com.mysql.jdbc.Driver");
			// 2、获得连接对象Connection
			Connection conection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=UTF-8", "root", "1234");
			// 3、写sql语句
			String sql = "SELECT id,name,age,gender,dept_id FROM user";
			// 4、创建Statement
			PreparedStatement statement = conection.prepareStatement(sql);
			// 5、执行sql语句
			// (1) 更新类（更改了表里面数据）：delete/update/insert executeUpdate()
			// 返回值：int，表示你影响的行数
			// (2)查询（没有改变表里面数据）: select executeQuery()
			// 返回值：结果集ResultSet
			ResultSet resultSet = statement.executeQuery();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				String gender = resultSet.getString("gender");
				int deptId = resultSet.getInt("dept_id");
				User user = new User(id, name, age, gender, deptId);
				list.add(user);
			}

			for (User user : list) {
				System.out.println(user);
			}
			// 6、关闭连接
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		// 把list集合放到request（一块内存）里面
		req.setAttribute("list", list);
		// 转发到user_list.jsp页面进行展示
		req.getRequestDispatcher("/user_list.jsp").forward(req, resp);
	}
}
